<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">



  <meta name="google-site-verification" content="k-_TfM33aVJFwi1JD8Y3HUhdvKJQH6zfXGr9IifVEas">














  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.png?v=5.1.3">


  <link rel="mask-icon" href="/images/favicon-32x32.png?v=5.1.3" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="````1. 配置文件Log4J配置文件的基本格式如下： #配置根Loggerlog4j.rootLogger  =   [ level ]   ,  appenderName1 ,  appenderName2 ,  … #配置日志信息输出目的地Appenderlog4j.appender.appenderName ">
<meta property="og:type" content="article">
<meta property="og:title" content="log4j-properties配置详解">
<meta property="og:url" content="https://angular2.top/posts/34754/index.html">
<meta property="og:site_name" content="大括号">
<meta property="og:description" content="````1. 配置文件Log4J配置文件的基本格式如下： #配置根Loggerlog4j.rootLogger  =   [ level ]   ,  appenderName1 ,  appenderName2 ,  … #配置日志信息输出目的地Appenderlog4j.appender.appenderName  =  fully.qualified.name.of.appender.cla">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-11-21T03:03:59.218Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="log4j-properties配置详解">
<meta name="twitter:description" content="````1. 配置文件Log4J配置文件的基本格式如下： #配置根Loggerlog4j.rootLogger  =   [ level ]   ,  appenderName1 ,  appenderName2 ,  … #配置日志信息输出目的地Appenderlog4j.appender.appenderName  =  fully.qualified.name.of.appender.cla">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://angular2.top/posts/34754/">





  <title>log4j-properties配置详解 | 大括号</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?8953b3d3866338b66f755c911e6136f4";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">大括号</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">是时候表演真正的技术了</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://angular2.top/posts/34754/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="无可替代">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/touxiang.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="大括号">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">log4j-properties配置详解</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-11-15T15:32:50+08:00">
                2017-11-15
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/我是一枚程序员/" itemprop="url" rel="index">
                    <span itemprop="name">我是一枚程序员</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i> 浏览
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>````<br><strong>1. 配置文件</strong>Log4J配置文件的基本格式如下：</p>
<p>#配置根Logger<br>log4j.rootLogger  =   [ level ]   ,  appenderName1 ,  appenderName2 ,  …</p>
<p>#配置日志信息输出目的地Appender<br>log4j.appender.appenderName  =  fully.qualified.name.of.appender.class<br>　　log4j.appender.appenderName.option1  =  value1<br>　　…<br>　　log4j.appender.appenderName.optionN  =  valueN </p>
<p>#配置日志信息的格式（布局）<br>log4j.appender.appenderName.layout  =  fully.qualified.name.of.layout.class<br>　　log4j.appender.appenderName.layout.option1  =  value1<br>　　…<br>　　log4j.appender.appenderName.layout.optionN  =  valueN<br>其中 <strong>[level] </strong>是日志输出级别，共有5级：<em>**</em></p>
<p>FATAL       0<br>ERROR      3<br>WARN       4<br>INFO         6<br>DEBUG      7 </p>
<p>Appender 为日志输出目的地，Log4j提供的appender有以下几种：<br>org.apache.log4j.ConsoleAppender（控制台），<br>org.apache.log4j.FileAppender（文件），<br>org.apache.log4j.DailyRollingFileAppender（每天产生一个日志文件），<br>org.apache.log4j.RollingFileAppender（文件大小到达指定尺寸的时候产生一个新的文件），<br>org.apache.log4j.WriterAppender（将日志信息以流格式发送到任意指定的地方）<br><strong>Layout</strong>：日志输出格式，Log4j提供的layout有以下几种：<br>org.apache.log4j.HTMLLayout（以HTML表格形式布局），<br>org.apache.log4j.PatternLayout（可以灵活地指定布局模式），<br>org.apache.log4j.SimpleLayout（包含日志信息的级别和信息字符串），<br>org.apache.log4j.TTCCLayout（包含日志产生的时间、线程、类别等等信息）<br><strong>打印参数: </strong>Log4J采用类似C语言中的printf函数的打印格式格式化日志信息，如下:</p>
<p> 　  <strong>%m</strong>   输出代码中指定的消息<br>　　<strong>%p</strong>   输出优先级，即DEBUG，INFO，WARN，ERROR，FATAL<br>　　<strong>%r</strong>   输出自应用启动到输出该log信息耗费的毫秒数<br>　　<strong>%c</strong>   输出所属的类目，通常就是所在类的全名<br>　　<strong>%t</strong>   输出产生该日志事件的线程名<br>　　<strong>%n </strong>  输出一个回车换行符，Windows平台为“\r\n”，Unix平台为“\n”<br>　　<strong>%d</strong>   输出日志时间点的日期或时间，默认格式为ISO8601，也可以在其后指定格式，比如：%d{yyy MMM dd HH:mm:ss , SSS}，输出类似：2002年10月18日  22 ： 10 ： 28， 921<br>　　<strong>%l </strong>  输出日志事件的发生位置，包括类目名、发生的线程，以及在代码中的行数。举例：Testlog4.main(TestLog4.java: 10 ) </p>
<p><strong>2. 在代码中初始化Logger:</strong> 1）在程序中调用<strong>BasicConfigurator.configure()</strong>方法：给根记录器增加一个ConsoleAppender，输出格式通过PatternLayout设为<strong>“%-4r [%t] %-5p %c %x - %m%n”</strong>，还有根记录器的默认级别是<strong>Level.DEBUG</strong>. 2）配置放在文件里，通过命令行参数传递文件名字，通过<strong>PropertyConfigurator.configure(args[x])</strong>解析并配置；3）配置放在文件里，通过环境变量传递文件名等信息，利用log4j默认的初始化过程解析并配置；4）配置放在文件里，通过应用服务器配置传递文件名等信息，利用一个特殊的servlet来完成配置。<br><strong>3. 为不同的 Appender 设置日志输出级别：</strong>当调试系统时，我们往往注意的只是异常级别的日志输出，但是通常所有级别的输出都是放在一个文件里的，如果日志输出的级别是BUG！？那就慢慢去找吧。这时我们也许会想要是能把异常信息单独输出到一个文件里该多好啊。当然可以，Log4j已经提供了这样的功能，我们只需要在配置中修改<strong>Appender</strong>的<strong>Threshold</strong> 就能实现,比如下面的例子：<br><strong>[配置文件]</strong></p>
<h3 id="set-log-levels"><a href="#set-log-levels" class="headerlink" title="set log levels"></a>set log levels</h3><p>log4j.rootLogger = debug ,  stdout ,  D ,  E</p>
<h3 id="输出到控制台"><a href="#输出到控制台" class="headerlink" title="输出到控制台"></a>输出到控制台</h3><p>log4j.appender.stdout = org.apache.log4j.ConsoleAppender<br>log4j.appender.stdout.Target = System.out<br>log4j.appender.stdout.layout = org.apache.log4j.PatternLayout<br>log4j.appender.stdout.layout.ConversionPattern =  %d{ABSOLUTE} %5p %c{ 1 }:%L - %m%n</p>
<h3 id="输出到日志文件"><a href="#输出到日志文件" class="headerlink" title="输出到日志文件"></a>输出到日志文件</h3><p>log4j.appender.D = org.apache.log4j.DailyRollingFileAppender<br>log4j.appender.D.File = logs/log.log<br>log4j.appender.D.Append = true<br>log4j.appender.D.<strong>Threshold</strong> = DEBUG <strong>## 输出DEBUG级别以上的日志</strong><br>log4j.appender.D.layout = org.apache.log4j.PatternLayout<br>log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n</p>
<h3 id="保存异常信息到单独文件"><a href="#保存异常信息到单独文件" class="headerlink" title="保存异常信息到单独文件"></a>保存异常信息到单独文件</h3><p>log4j.appender.D = org.apache.log4j.DailyRollingFileAppender<br>log4j.appender.D.File = logs/error.log ## 异常日志文件名<br>log4j.appender.D.Append = true<br>log4j.appender.D.<strong>Threshold</strong> = ERROR<strong> ## 只输出ERROR级别以上的日志!!!</strong><br>log4j.appender.D.layout = org.apache.log4j.PatternLayout<br>log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n<br><strong>[代码中使用]</strong> </p>
<p> public   class  TestLog4j  {</p>
<pre><code> public   static   void  main(String[] args)  {
    PropertyConfigurator.configure( &quot; D:/Code/conf/log4j.properties &quot; );
    Logger logger  =  Logger.getLogger(TestLog4j. class );
    logger.debug( &quot; debug &quot; );
    logger.error( &quot; error &quot; );
} 
</code></pre><p>}<br>运行一下，看看异常信息是不是保存在了一个单独的文件error.log中<br>log4j.properties 使用一.参数意义说明输出级别的种类ERROR、WARN、INFO、DEBUGERROR 为严重错误 主要是程序的错误WARN 为一般警告，比如session丢失INFO 为一般要显示的信息，比如登录登出DEBUG 为程序的调试信息配置日志信息输出目的地log4j.appender.appenderName = fully.qualified.name.of.appender.class1.org.apache.log4j.ConsoleAppender（控制台）2.org.apache.log4j.FileAppender（文件）3.org.apache.log4j.DailyRollingFileAppender（每天产生一个日志文件）4.org.apache.log4j.RollingFileAppender（文件大小到达指定尺寸的时候产生一个新的文件）5.org.apache.log4j.WriterAppender（将日志信息以流格式发送到任意指定的地方）配置日志信息的格式log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class1.org.apache.log4j.HTMLLayout（以HTML表格形式布局），2.org.apache.log4j.PatternLayout（可以灵活地指定布局模式），3.org.apache.log4j.SimpleLayout（包含日志信息的级别和信息字符串），4.org.apache.log4j.TTCCLayout（包含日志产生的时间、线程、类别等等信息）控制台选项Threshold=DEBUG:指定日志消息的输出最低层次。ImmediateFlush=true:默认值是true,意谓着所有的消息都会被立即输出。Target=System.err：默认情况下是：System.out,指定输出控制台FileAppender 选项Threshold=DEBUF:指定日志消息的输出最低层次。ImmediateFlush=true:默认值是true,意谓着所有的消息都会被立即输出。File=mylog.txt:指定消息输出到mylog.txt文件。Append=false:默认值是true,即将消息增加到指定文件中，false指将消息覆盖指定的文件内容。RollingFileAppender 选项Threshold=DEBUG:指定日志消息的输出最低层次。ImmediateFlush=true:默认值是true,意谓着所有的消息都会被立即输出。File=mylog.txt:指定消息输出到mylog.txt文件。Append=false:默认值是true,即将消息增加到指定文件中，false指将消息覆盖指定的文件内容。MaxFileSize=100KB: 后缀可以是KB, MB 或者是 GB. 在日志文件到达该大小时，将会自动滚动，即将原来的内容移到mylog.log.1文件。MaxBackupIndex=2:指定可以产生的滚动文件的最大数。log4j.appender.A1.layout.ConversionPattern=%-4r %-5p %d{yyyy-MM-dd HH:mm:ssS} %c %m%n日志信息格式中几个符号所代表的含义： -X号: X信息输出时左对齐； %p: 输出日志信息优先级，即DEBUG，INFO，WARN，ERROR，FATAL, %d: 输出日志时间点的日期或时间，默认格式为ISO8601，也可以在其后指定格式，比如：%d{yyy MMM dd HH:mm:ss,SSS}，输出类似：2002年10月18日 22：10：28，921 %r: 输出自应用启动到输出该log信息耗费的毫秒数 %c: 输出日志信息所属的类目，通常就是所在类的全名 %t: 输出产生该日志事件的线程名 %l: 输出日志事件的发生位置，相当于%C.%M(%F:%L)的组合,包括类目名、发生的线程，以及在代码中的行数。举例：Testlog4.main (TestLog4.java:10) %x: 输出和当前线程相关联的NDC(嵌套诊断环境),尤其用到像java servlets这样的多客户多线程的应用中。 %%: 输出一个”%”字符 %F: 输出日志消息产生时所在的文件名称 %L: 输出代码中的行号 %m: 输出代码中指定的消息,产生的日志具体信息 %n: 输出一个回车换行符，Windows平台为”\r\n”，Unix平台为”\n”输出日志信息换行 可以在%与模式字符之间加上修饰符来控制其最小宽度、最大宽度、和文本的对齐方式。如： 1)%20c：指定输出category的名称，最小的宽度是20，如果category的名称小于20的话，默认的情况下右对齐。 2)%-20c:指定输出category的名称，最小的宽度是20，如果category的名称小于20的话，”-“号指定左对齐。 3)%.30c:指定输出category的名称，最大的宽度是30，如果category的名称大于30的话，就会将左边多出的字符截掉，但小于30的话也不会有空格。 4)%20.30c:如果category的名称小于20就补空格，并且右对齐，如果其名称长于30字符，就从左边较远输出的字符截掉。二.文件配置Sample1log4j.rootLogger=DEBUG,A1,R#log4j.rootLogger=INFO,A1,R# ConsoleAppender 输出log4j.appender.A1=org.apache.log4j.ConsoleAppenderlog4j.appender.A1.layout=org.apache.log4j.PatternLayoutlog4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%c]-[%p] %m%n# File 输出 一天一个文件,输出路径可以定制,一般在根路径下log4j.appender.R=org.apache.log4j.DailyRollingFileAppenderlog4j.appender.R.File=blog_log.txtlog4j.appender.R.MaxFileSize=500KBlog4j.appender.R.MaxBackupIndex=10log4j.appender.R.layout=org.apache.log4j.PatternLayoutlog4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n文件配置Sample2下面给出的Log4J配置文件实现了输出到控制台，文件，回滚文件，发送日志邮件，输出到数据库日志表，自定义标签等全套功能。log4j.rootLogger=DEBUG,CONSOLE,A1,im #DEBUG,CONSOLE,FILE,ROLLING_FILE,MAIL,DATABASElog4j.addivity.org.apache=true################### # Console Appender ################### log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.Threshold=DEBUG log4j.appender.CONSOLE.Target=System.out log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n #log4j.appender.CONSOLE.layout.ConversionPattern=[start]%d{DATE}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t[THREAD] n%c[CATEGORY]%n%m[MESSAGE]%n%n##################### # File Appender ##################### log4j.appender.FILE=org.apache.log4j.FileAppender log4j.appender.FILE.File=file.log log4j.appender.FILE.Append=false log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n # Use this layout for LogFactor 5 analysis######################## # Rolling File ######################## log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender log4j.appender.ROLLING_FILE.Threshold=ERROR log4j.appender.ROLLING_FILE.File=rolling.log log4j.appender.ROLLING_FILE.Append=true log4j.appender.ROLLING_FILE.MaxFileSize=10KB log4j.appender.ROLLING_FILE.MaxBackupIndex=1 log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout log4j.appender.ROLLING_FILE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n#################### # Socket Appender #################### log4j.appender.SOCKET=org.apache.log4j.RollingFileAppender log4j.appender.SOCKET.RemoteHost=localhost log4j.appender.SOCKET.Port=5001 log4j.appender.SOCKET.LocationInfo=true # Set up for Log Facter 5 log4j.appender.SOCKET.layout=org.apache.log4j.PatternLayout log4j.appender.SOCET.layout.ConversionPattern=[start]%d{DATE}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t[THREAD]%n%c[CATEGORY]%n%m[MESSAGE]%n%n######################## # Log Factor 5 Appender ######################## log4j.appender.LF5_APPENDER=org.apache.log4j.lf5.LF5Appender log4j.appender.LF5_APPENDER.MaxNumberOfRecords=2000######################## # SMTP Appender ####################### log4j.appender.MAIL=org.apache.log4j.net.SMTPAppender log4j.appender.MAIL.Threshold=FATAL log4j.appender.MAIL.BufferSize=10 <a href="mailto:log4j.appender.MAIL.From=chenyl@yeqiangwei.com" rel="external nofollow noopener noreferrer" target="_blank">log4j.appender.MAIL.From=chenyl@yeqiangwei.com</a>log4j.appender.MAIL.SMTPHost=mail.hollycrm.com log4j.appender.MAIL.Subject=Log4J Message <a href="mailto:log4j.appender.MAIL.To=chenyl@yeqiangwei.com" rel="external nofollow noopener noreferrer" target="_blank">log4j.appender.MAIL.To=chenyl@yeqiangwei.com</a>log4j.appender.MAIL.layout=org.apache.log4j.PatternLayout log4j.appender.MAIL.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n######################## # JDBC Appender ####################### log4j.appender.DATABASE=org.apache.log4j.jdbc.JDBCAppender log4j.appender.DATABASE.URL=jdbc:mysql://localhost:3306/test log4j.appender.DATABASE.driver=com.mysql.jdbc.Driver log4j.appender.DATABASE.user=root log4j.appender.DATABASE.password= log4j.appender.DATABASE.sql=INSERT INTO LOG4J (Message) VALUES (‘[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n’) log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout log4j.appender.DATABASE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%nlog4j.appender.A1=org.apache.log4j.DailyRollingFileAppender log4j.appender.A1.File=SampleMessages.log4j log4j.appender.A1.DatePattern=yyyyMMdd-HH’.log4j’ log4j.appender.A1.layout=org.apache.log4j.xml.XMLLayout################### #自定义Appender ################### log4j.appender.im = net.cybercorlin.util.logger.appender.IMAppenderlog4j.appender.im.host = mail.cybercorlin.net log4j.appender.im.username = username log4j.appender.im.password = password log4j.appender.im.recipient = <a href="mailto:corlin@yeqiangwei.com" rel="external nofollow noopener noreferrer" target="_blank">corlin@yeqiangwei.com</a>log4j.appender.im.layout=org.apache.log4j.PatternLayout log4j.appender.im.layout.ConversionPattern =[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n三.高级使用实验目的： 1.把FATAL级错误写入2000NT日志 2. WARN，ERROR，FATAL级错误发送email通知管理员 3.其他级别的错误直接在后台输出实验步骤： 输出到2000NT日志 1.把Log4j压缩包里的NTEventLogAppender.dll拷到WINNT\SYSTEM32目录下 2.写配置文件log4j.properties# 在2000系统日志输出 log4j.logger.NTlog=FATAL, A8 # APPENDER A8 log4j.appender.A8=org.apache.log4j.nt.NTEventLogAppender log4j.appender.A8.Source=JavaTest log4j.appender.A8.layout=org.apache.log4j.PatternLayout log4j.appender.A8.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n3.调用代码： Logger logger2 = Logger.getLogger(“NTlog”); //要和配置文件中设置的名字相同 logger2.debug(“debug!!!”); logger2.info(“info!!!”); logger2.warn(“warn!!!”); logger2.error(“error!!!”); //只有这个错误才会写入2000日志 logger2.fatal(“fatal!!!”);发送email通知管理员： 1. 首先下载JavaMail和JAF,   <a href="http://java.sun.com/j2ee/ja/javamail/index.html" rel="external nofollow noopener noreferrer" target="_blank">http://java.sun.com/j2ee/ja/javamail/index.html</a>  <a href="http://java.sun.com/beans/glasgow/jaf.html" rel="external nofollow noopener noreferrer" target="_blank">http://java.sun.com/beans/glasgow/jaf.html</a> 在项目中引用mail.jar和activation.jar。 2. 写配置文件 # 将日志发送到email log4j.logger.MailLog=WARN,A5 #  APPENDER A5 log4j.appender.A5=org.apache.log4j.net.SMTPAppender log4j.appender.A5.BufferSize=5 <a href="mailto:log4j.appender.A5.To=chunjie@yeqiangwei.com" rel="external nofollow noopener noreferrer" target="_blank">log4j.appender.A5.To=chunjie@yeqiangwei.com</a> <a href="mailto:log4j.appender.A5.From=error@yeqiangwei.com" rel="external nofollow noopener noreferrer" target="_blank">log4j.appender.A5.From=error@yeqiangwei.com</a> log4j.appender.A5.Subject=ErrorLog log4j.appender.A5.SMTPHost=smtp.263.net log4j.appender.A5.layout=org.apache.log4j.PatternLayout log4j.appender.A5.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n 3.调用代码： //把日志发送到mail Logger logger3 = Logger.getLogger(“MailLog”); logger3.warn(“warn!!!”); logger3.error(“error!!!”); logger3.fatal(“fatal!!!”);在后台输出所有类别的错误： 1. 写配置文件 # 在后台输出 log4j.logger.console=DEBUG, A1 # APPENDER A1 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n 2．调用代码 Logger logger1 = Logger.getLogger(“console”); logger1.debug(“debug!!!”); logger1.info(“info!!!”); logger1.warn(“warn!!!”); logger1.error(“error!!!”); logger1.fatal(“fatal!!!”);——————————————————————– 全部配置文件：log4j.properties # 在后台输出 log4j.logger.console=DEBUG, A1 # APPENDER A1 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n# 在2000系统日志输出 log4j.logger.NTlog=FATAL, A8 # APPENDER A8 log4j.appender.A8=org.apache.log4j.nt.NTEventLogAppender log4j.appender.A8.Source=JavaTest log4j.appender.A8.layout=org.apache.log4j.PatternLayout log4j.appender.A8.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n# 将日志发送到email log4j.logger.MailLog=WARN,A5 #  APPENDER A5 log4j.appender.A5=org.apache.log4j.net.SMTPAppender log4j.appender.A5.BufferSize=5 <a href="mailto:log4j.appender.A5.To=chunjie@yeqiangwei.com" rel="external nofollow noopener noreferrer" target="_blank">log4j.appender.A5.To=chunjie@yeqiangwei.com</a> <a href="mailto:log4j.appender.A5.From=error@yeqiangwei.com" rel="external nofollow noopener noreferrer" target="_blank">log4j.appender.A5.From=error@yeqiangwei.com</a> log4j.appender.A5.Subject=ErrorLog log4j.appender.A5.SMTPHost=smtp.263.net log4j.appender.A5.layout=org.apache.log4j.PatternLayout log4j.appender.A5.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n全部代码：Log4jTest.java  /<em>   </em> 创建日期 2003-11-13   <em>/  package edu.bcu.Bean;  import org.apache.log4j.</em>;  //import org.apache.log4j.nt.<em>;  //import org.apache.log4j.net.</em>;  /<em>*   </em> @author yanxu   */  public class Log4jTest  {   public static void main(String args[])   {    PropertyConfigurator.configure(“log4j.properties”);    //在后台输出    Logger logger1 = Logger.getLogger(“console”);    logger1.debug(“debug!!!”);    logger1.info(“info!!!”);    logger1.warn(“warn!!!”);    logger1.error(“error!!!”);    logger1.fatal(“fatal!!!”);//在NT系统日志输出    Logger logger2 = Logger.getLogger(“NTlog”);    //NTEventLogAppender nla = new NTEventLogAppender();    logger2.debug(“debug!!!”);    logger2.info(“info!!!”);    logger2.warn(“warn!!!”);    logger2.error(“error!!!”);    //只有这个错误才会写入2000日志    logger2.fatal(“fatal!!!”);//把日志发送到mail    Logger logger3 = Logger.getLogger(“MailLog”);    //SMTPAppender sa = new SMTPAppender();    logger3.warn(“warn!!!”);    logger3.error(“error!!!”);    logger3.fatal(“fatal!!!”);   }  }</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>文章不错，你都不请我喝杯茶，就是说你呀！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="无可替代 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="无可替代 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/22617/" rel="next" title="angular系列教程看这里">
                <i class="fa fa-chevron-left"></i> angular系列教程看这里
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/touxiang.jpg" alt="无可替代">
            
              <p class="site-author-name" itemprop="name">无可替代</p>
              <p class="site-description motion-element" itemprop="description">大括号的博客</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">129</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/liepeng328" target="_blank" title="GitHub" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://gitee.com/lovepeng" target="_blank" title="码云" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>码云</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://coding.net/u/dakuohao" target="_blank" title="Coding" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>Coding</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.toutiao.com/c/user/2585432515/#mid=6741594486" target="_blank" title="今日头条" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>今日头条</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/dakuohao/activities" target="_blank" title="知乎" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>知乎</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://www.jianshu.com/u/4ea0af17fd67" target="_blank" title="简书" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>简书</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&email=hOjr8uH04erjt7a8xPX1qufr6Q" target="_blank" title="E-Mail" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://jq.qq.com/?_wv=1027&k=5ISEgpc" target="_blank" title="QQ群" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>QQ群</a>
                </span>
              
            
          </div>

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#set-log-levels"><span class="nav-number">1.</span> <span class="nav-text">set log levels</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#输出到控制台"><span class="nav-number">2.</span> <span class="nav-text">输出到控制台</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#输出到日志文件"><span class="nav-number">3.</span> <span class="nav-text">输出到日志文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#保存异常信息到单独文件"><span class="nav-number">4.</span> <span class="nav-text">保存异常信息到单独文件</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">无可替代</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io" rel="external nofollow noopener noreferrer">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow noopener noreferrer">NexT.Pisces</a> v5.1.3</div>



<span class="post-meta-divider">|</span>
<div class="theme-info">
Hosted by <a class="theme-link" target="_blank" href="https://pages.coding.me" rel="external nofollow noopener noreferrer">Coding Pages</a>
</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i> 访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 访问总量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  



  
  









  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
